<?php

/**
 * 登陆控制器
 * @author jackson.xu@wemax.org
 */

namespace Admin\Controller;

use Think\Controller;
use Org\Util\Rbac;

/**
 * Description of LoginController
 *
 * @author Administrator
 */
class LoginController extends Controller {

    //登录首页
    public function index() {
        $this->display();
    }

    public function login() {
        if (!IS_POST)
            E('页面不存在');

        //获取参数
        $username = I('username');
        $pwd = I('password', '', 'md5');


        //用户账号密码检测
        $user = M('users')->where(array('name' => $username))->find();
        if (!$user || $user['password'] != $pwd) {
            $this->error('用户账号或者密码错误');
        }

        if ($user['is_active']) {
            $this->error('用户被锁定');
        }

        //更新用户信息
        $data = array(
            'id' => $user['id'],
            'last_login' => time(),
            'logins' => $user['logins'] + 1,
        );
        M('users')->save($data);

        //写入session
        session(C('USER_AUTH_KEY'), $user['id']);
        session('bg_username', $user['name']);
        session('logintime', date('Y-m-d H:i:s'), $user['last_login']);

        //识别超级管理员，并修改session
        if ($user['name'] == C('RBAC_SUPERADMIN')) {
            session(C('ADMIN_AUTH_KEY'), TRUE);
        }

        //读取用户权限
        new \Org\Util\Rbac();
        Rbac::saveAccessList();

        //到后台主页
        $this->redirect('Admin/Index/index');
    }

    //验证码生成
    public function verify() {
        ob_clean();
        $config = array(
            'fontSize' => 20, // 验证码字体大小   
            'length' => 4, // 验证码位数    
            'useNoise' => false, // 关闭验证码杂点
        );
        $Verify = new \Think\Verify($config);
        $Verify->codeSet = '0123456789';
        $Verify->entry();
    }

    //检测验证码是否正确
    function check_verify($code, $id = '') {
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }

    //退出登陆
    public function logout() {
        session(null);
        $this->redirect('Login/index');
    }

    //验证
    public function doLogin() {
        $data = I('post.');

        //验证码检测
        $verfity = $this->check_verify($data['code'], '');
        if (!$verfity) {
            $this->ajaxReturn('code');
        }

        //用户检测
        $map['name'] = $data['name'];
        $pwd = M('users')->where($map)->getField('password');
        if (!$pwd) {
            $this->ajaxReturn('user');
        }
        //密码检测
        if ($pwd != md5($data['pwd'])) {
            $this->ajaxReturn('pwd');
        }

        $this->ajaxReturn('true');
    }

}

?>
